package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;
import java.nio.ByteBuffer;

public class GetRequestNext extends AxdrType {
    private ByteBuffer dataCode = null;
    private PIID piid = null;
    private Unsigned16 dataIndex = null;

    public void setDataCode(ByteBuffer dataCode) {
        this.dataCode = dataCode;
    }

    public void setPiid(PIID piid) {
        this.piid = piid;
    }

    public void setDataIndex(Unsigned16 dataIndex) {
        this.dataIndex = dataIndex;
    }

    public void setAll(PIID piid, Unsigned16 dataIndex) {
        this.piid = piid;
        this.dataIndex = dataIndex;
    }

    public GetRequestNext() {
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.piid = new PIID();
        this.piid.setNumBit(8);
        codeLength += this.piid.decode(input);
        this.dataIndex = new Unsigned16();
        this.dataIndex.setConst();
        codeLength += this.dataIndex.decode(input);
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength = 0;
        if (this.dataCode != null) {
            byte[] data = dataCode.array();
            codeLength = data.length;
            for (int i = data.length - 1; i >= 0; i--) {
                output.write(data[i]);
            }
        } else {
            if (this.piid != null && this.dataIndex != null) {
                codeLength += this.dataIndex.encode(output);
                codeLength += this.piid.encode(output);
            } else {
                throw new Exception("PIID or dataIndex is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = ByteBuffer.wrap(revOStream.toByteArray());
    }

    @Override
    public String toString() {
        if (this.piid != null && this.dataIndex != null) {
            return "sequence: {" + "piid: " + this.piid + ", dataIndex: " + this.dataIndex + "}";
        } else {
            return "piid || dataIndex is null";
        }
    }
}



